package com.ltkj.baseplatform.service.impl;

import com.ltkj.baseplatform.domain.ArtChannel;
import com.ltkj.baseplatform.domain.ArtCollection;
import com.ltkj.baseplatform.domain.bo.ArtChannelBo;
import com.ltkj.baseplatform.domain.bo.ArtChannelQueryBo;
import com.ltkj.baseplatform.domain.vo.TreeSelect;
import com.ltkj.baseplatform.mapper.ArtChannelBusinessMapper;
import com.ltkj.baseplatform.mapper.ArtChannelMapper;
import com.ltkj.baseplatform.mapper.ArtCollectionBusinessMapper;
import com.ltkj.baseplatform.service.IArtChannelService;
import com.ltkj.common.core.constant.CacheConstants;
import com.ltkj.common.core.exception.ServiceException;
import com.ltkj.common.core.utils.DateUtils;
import com.ltkj.common.core.utils.SpringUtils;
import com.ltkj.common.core.utils.StringUtils;
import com.ltkj.common.redis.service.RedisService;
import com.ltkj.common.security.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 文章管理-栏目Service业务层处理
 * 
 * @author liupf
 * @date 2023-08-28
 */
@Service
public class ArtChannelServiceImpl implements IArtChannelService 
{
    @Autowired
    private ArtChannelMapper artChannelMapper;

    @Autowired
    private ArtChannelBusinessMapper artChannelBusinessMapper;

    @Autowired
    private ArtCollectionBusinessMapper artCollectionBusinessMapper;

    @Autowired
    private RedisService redisService;

    /**
     * 查询文章管理-栏目
     * 
     * @param id 文章管理-栏目主键
     * @return 文章管理-栏目
     */
    @Override
    public ArtChannel selectArtChannelById(Long id)
    {
        return artChannelMapper.selectArtChannelById(id);
    }

    /**
     * 查询文章管理-栏目列表
     * 
     * @param artChannel 文章管理-栏目
     * @return 文章管理-栏目
     */
    @Override
    public List<ArtChannel> selectArtChannelList(ArtChannel artChannel)
    {
        return artChannelMapper.selectArtChannelList(artChannel);
    }
    /**
     * 根据id集合查询栏目列表
     *
     * @param ids 栏目id集合
     * @return 文章管理-栏目集合
     */
    @Override
    public List<ArtChannel> selectChannelListByIds(Long[] ids) {
        return artChannelBusinessMapper.selectChannelListByIds(ids);
    }

    /**
     * 新增文章管理-栏目
     * 
     * @param artChannelBo 文章管理-栏目
     * @return 结果
     */
    @Override
    public int insertArtChannel(ArtChannelBo artChannelBo)
    {
        ArtChannel artChannel = new ArtChannel();
        BeanUtils.copyProperties(artChannelBo,artChannel);
        artChannel.setCreateTime(DateUtils.getNowDate());
        artChannel.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        validEntityBeforeSave(artChannel);
        int i = artChannelMapper.insertArtChannel(artChannel);
        //添加栏目成功就移除缓存，首页使用
        if (i > 0){
            redisService.deleteObject(CacheConstants.HOME_ELE_DATA_KEY);
        }
        return i;
    }

    /**
     * 修改文章管理-栏目
     * 
     * @param artChannelBo 文章管理-栏目
     * @return 结果
     */
    @Override
    public int updateArtChannel(ArtChannelBo artChannelBo)
    {
        ArtChannel artChannel = new ArtChannel();
        BeanUtils.copyProperties(artChannelBo,artChannel);
        artChannel.setUpdateTime(DateUtils.getNowDate());
        artChannel.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
        validEntityBeforeEdit(artChannel);
        int i = artChannelMapper.updateArtChannel(artChannel);
        //修改栏目成功就移除缓存，首页使用
        if (i > 0){
            redisService.deleteObject(CacheConstants.HOME_ELE_DATA_KEY);
        }
        return i;
    }

    /**
     * 批量删除文章管理-栏目
     * 
     * @param ids 需要删除的文章管理-栏目主键
     * @return 结果
     */
    @Override
    public int deleteArtChannelByIds(Long[] ids)
    {
        int i = artChannelMapper.updateChannelDelFlagByIds(ids);
        //删除栏目成功就移除缓存，首页使用
        if (i > 0){
            redisService.deleteObject(CacheConstants.HOME_ELE_DATA_KEY);
        }
        return i;
    }

    /**
     * 删除文章管理-栏目信息
     * 
     * @param id 文章管理-栏目主键
     * @return 结果
     */
    @Override
    public int deleteArtChannelById(Long id)
    {
        return artChannelMapper.deleteArtChannelById(id);
    }

    /**
     * 查询栏目树结构信息
     * @return 栏目树信息集合
     */
    @Override
    public List<TreeSelect> selectChannelTreeList() {
        List<ArtChannel> list = artChannelBusinessMapper.selectArtChannelList(new ArtChannelQueryBo());
        List<ArtChannel> channelTrees = buildChannelTree(list);
        return channelTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 将传入的栏目数据放入回收站
     *
     * @param ids id集合
     * @return 结果
     */
    @Transactional
    @Override
    public int recycle(Long[] ids,List<ArtChannel> list) {
        int result = artChannelBusinessMapper.recycle(ids);
        String userName = SecurityUtils.getLoginUser().getUsername();
        Date nowDate = DateUtils.getNowDate();
        List<ArtCollection> collections = new ArrayList<>();
        //将数据放到回收站表
        for (ArtChannel channel : list) {
            ArtCollection collection = new ArtCollection();
            collection.setContentId(channel.getId());
            collection.setCollectName(channel.getChannelName());
            collection.setType("0");
            collection.setIsDel("0");
            collection.setCreateBy(userName);
            collection.setCreateTime(nowDate);
            collections.add(collection);
        }
        if(!CollectionUtils.isEmpty(collections)){
            artCollectionBusinessMapper.insertBatch(collections);
        }
        return result;
    }

    @Override
    public List<ArtChannel> selectArtChannelList(ArtChannelQueryBo artChannelQueryBo) {
        return artChannelBusinessMapper.selectArtChannelList(artChannelQueryBo);
    }

    @Override
    public boolean hasChildByChannelId(Long channelId) {
        return artChannelMapper.hasChildByChannelId(channelId) > 0;
    }

    @Override
    public boolean checkChannelExistContent(Long channelId) {
        return artChannelMapper.checkChannelExistContent(channelId) > 0;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param artChannels 栏目列表
     * @return 树结构列表
     */
    private List<ArtChannel> buildChannelTree(List<ArtChannel> artChannels)
    {
        List<ArtChannel> returnList = new ArrayList<>();
        List<Long> tempList = artChannels.stream().map(ArtChannel::getId).collect(Collectors.toList());
        for (ArtChannel channel : artChannels)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(channel.getParentId()))
            {
                recursionFn(artChannels, channel);
                returnList.add(channel);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = artChannels;
        }
        return returnList;
    }
    /**
     * 递归列表
     */
    private void recursionFn(List<ArtChannel> list, ArtChannel t)
    {
        // 得到子节点列表
        List<ArtChannel> childList = getChildList(list, t);
        t.setChildren(childList);
        for (ArtChannel tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }
    /**
     * 得到子节点列表
     */
    private List<ArtChannel> getChildList(List<ArtChannel> list, ArtChannel t)
    {
        List<ArtChannel> tlist = new ArrayList<>();
        Iterator<ArtChannel> it = list.iterator();
        while (it.hasNext())
        {
            ArtChannel n = it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<ArtChannel> list, ArtChannel t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    /**
     * 新增数据前的数据校验
     */
    private void validEntityBeforeSave(ArtChannel entity){
        int num = artChannelBusinessMapper.isRepeat(entity);
        if(num > 0){
            throw new ServiceException("栏目名称不能重复！");
        }
    }

    /**
     * 编辑数据前的数据校验
     */
    private void validEntityBeforeEdit(ArtChannel entity){
        int num = artChannelBusinessMapper.isRepeatExcludeSelf(entity);
        if(num > 0){
            throw new ServiceException("栏目名称不能重复！");
        }
    }
}
